<template>
  <el-select v-model="selectedSectionId" clearable filterable remote reserve-keyword placeholder="请选择章节"
    :remote-method="remoteSearch" :loading="loading" size="small" @change="handleChange"
    :style="{ width: selectWidth + 'px' }">
    <el-option v-for="item in sectionList" :key="item.id" :label="item.sectionName" :value="item.id">
    </el-option>
  </el-select>
</template>

<script>
import api from '@/common/api'

export default {
  name: 'CourseSectionSelect',
  props: {
    value: {
      type: [Number, String],
      default: null
    },
    courseId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      sectionList: [],
      loading: false,
      selectedSectionId: this.value,      
    }
  },
  computed: {
    selectWidth() {
      return this.selectedSectionId ? 200 : 120
    }
  },
  watch: {
    value(newVal) {
      this.selectedSectionId = newVal;
    },
    courseId(newVal) {
      this.loadSections(newVal);
    }
  },
  created() {
    this.loadSections(this.courseId);
    if (this.value) {
      this.loadSelectedSection(this.value);
    }
  },
  methods: {
    loadSelectedSection(sectionId) {
      this.selectedSectionId = sectionId;
    },
    remoteSearch(query) {
      if (!this.courseId) {
        this.sectionList = [];
        return;
      }
      this.loading = true;
      const params = {
        keyword: query,
        courseId: this.courseId
      };
      api.admin_getCourseSectionList(params).then(response => {
        this.sectionList = response.data.data.records;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleChange(val) {
      this.$emit('input', val);
      this.$emit('change', val);
    },
    loadSections(courseId) {
      if (!courseId) {
        this.sectionList = [];
        return;
      }
      this.loading = true;
      api.admin_getCourseSectionList({ courseId }).then(response => {
        this.sectionList = response.data.data.records;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    }
  }
}
</script>

<style scoped>
.el-select {
  display: inline-block;
  transition: width 0.3s;
}

.el-select:hover, .el-select:has(.is-focus) {
  width: 200px !important;
}
</style>
